
//
//  HomeStarViewController.m
//  LiveStar
//
//  Created by 漪珊 on 2016/12/9.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "HomeStarViewController.h"
#import "HomeStarCell.h"
#import "SetPredictViewController.h"
#import "LivingViewController.h"
#import "MessageViewController.h"
#import "HomeStarTopView.h"
#import "StarHomeModel.h"
#define MaxIconWH  70.0  //用户头像最大的尺寸
#define MaxIconCenterY  44 // 头像最大的centerY


@interface HomeStarViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray *_homeArr;//首页预播列表数组
    NSMutableArray *_orderbyDateArray; //排序后的数组
}
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)UIImageView *starImgView;
@end

@implementation HomeStarViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.navigationController.navigationBar addSubview:self.starImgView];
}
- (void)viewWillDisappear:(BOOL)animated {
    [self.starImgView removeFromSuperview];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNav];
    [self StarHomeRequset];
    [self setUpUI];
    _homeArr = [NSMutableArray arrayWithCapacity:1];
    _orderbyDateArray = [NSMutableArray arrayWithCapacity:1];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ReloadData:) name:kStarHomeNotifica object:nil];
    // Do any additional setup after loading the view.
}

- (void)ReloadData:(NSNotification *)notifica {
    [self StarHomeRequset];
}

#pragma mark -- 明星首页请求
- (void)StarHomeRequset {
    NSDictionary *dict = @{
                           @"udid":User_ID,
                           @"token":TOKEN
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kStarHome];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        NSArray *array = responseObject[@"data"][@"list"];
        if (_homeArr.count>0) {
            [_homeArr removeAllObjects];
        }
        for (NSDictionary *homeDic in array) {
            StarHomeModel *model = [[StarHomeModel alloc] initWithDict:homeDic];
            [_homeArr addObject:model];
        }
        [self OrderDateByDateWihthListArray:_homeArr];
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}

- (void)OrderDateByDateWihthListArray:(NSMutableArray *)array {
    [_orderbyDateArray removeAllObjects];
    NSMutableArray *timeArr=[NSMutableArray array];
    [_homeArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        
        StarHomeModel *model = obj;
        NSArray *dateArray = [model.l_date componentsSeparatedByString:@"-"];
        NSString *month1= dateArray[1];
        NSString *day1= dateArray[2];
        NSString *currentStr1=[month1 stringByAppendingString:day1];
        [timeArr addObject:currentStr1];
    }];
    //使用asset把timeArr的日期去重
    NSSet *set = [NSSet setWithArray:timeArr];
    NSArray *userArray = [set allObjects];
    NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES];//yes升序排列，no,降序排列
    //按日期降序排列的日期数组
    NSArray *myary = [userArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd1, nil]];
    [myary enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSMutableArray *arr = [NSMutableArray array];
        [_orderbyDateArray addObject:arr];
        
    }];
    [_homeArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        StarHomeModel *model = obj;
        NSArray *dateArray = [model.l_date componentsSeparatedByString:@"-"];
        NSString *month1= dateArray[1];
        NSString *day1= dateArray[2];
        NSString *currentStr1=[month1 stringByAppendingString:day1];
        for (NSString *str in myary)
        {
            if([str isEqualToString:currentStr1])
            {
                NSMutableArray *arr=[_orderbyDateArray objectAtIndex:[myary indexOfObject:str]];
                [arr addObject:model];
            }
        }
        
    }];
   [self.tableView reloadData];
}
#pragma mark -- setUpUI
- (void)setUpUI {
    [self creatStarImageView];
    [self creatTabelView];

}

// 创建明星头像
- (void)creatStarImageView {
    self.starImgView = [[UIImageView alloc] init];
    [self.starImgView sd_setImageWithURL:[NSURL URLWithString:[[LSUserInfoManager sharedManager] currentUserInfo].u_avatar] placeholderImage:[UIImage imageNamed:@"userPhoto"]];
    self.starImgView.backgroundColor = [UIColor darkGrayColor];
    self.starImgView.bounds = CGRectMake(0, 0, MaxIconWH, MaxIconWH);
    self.starImgView.center = CGPointMake(kSCREEN_WIDTH*0.5, MaxIconCenterY);
    self.starImgView.contentMode = UIViewContentModeScaleAspectFill;
    self.starImgView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.starImgView.layer.borderWidth = 1.2;
    self.starImgView.layer.cornerRadius = MaxIconWH/2.0;
    self.starImgView.layer.masksToBounds = YES;
}


- (void)creatTabelView {
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = NO;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableHeaderView = [self setTopView];
    [self.view addSubview:self.tableView];
}

- (UIView *)setTopView {
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, 220)];
    UILabel *name = [[UILabel alloc] init];
    
    name.text = [[LSUserInfoManager sharedManager] currentUserInfo].u_nickname;
    UIButton *liveBtn = [[UIButton alloc] init];
    liveBtn.backgroundColor = [UIColor mainColor];
    [liveBtn setTitle:@"直播" forState:UIControlStateNormal];
    UIButton *setBtn = [[UIButton alloc] init];
    [liveBtn addTarget:self action:@selector(BeginLiving:) forControlEvents:UIControlEventTouchUpInside];
    setBtn.backgroundColor = [UIColor whiteColor];
    [setBtn setTitleColor:[UIColor mainColor] forState:UIControlStateNormal];
    [setBtn setTitle:@"设定" forState:UIControlStateNormal];
    [setBtn addTarget:self action:@selector(PredictClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *sepline = [[UIView alloc] init];
    sepline.backgroundColor = HESHEX_COLOR(@"E9EDF2");
    UILabel *predictTitle = [[UILabel alloc] init];
    predictTitle.text = @"预播列表";
    predictTitle.font = UIFont(13);
    predictTitle.textColor = HESHEX_COLOR(@"999999");
    
    kButtonRadius(liveBtn, 5);
    kButtonBorderRadius(setBtn, 5, 0.5, [UIColor mainColor]);
    
    [topView addSubview:name];
    [topView addSubview:liveBtn];
    [topView addSubview:setBtn];
    [topView addSubview:sepline];
    [topView addSubview:predictTitle];
    
    [name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(topView);
        make.top.mas_equalTo(topView.mas_top).offset(43);
    }];
    
    [liveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(topView.mas_left).offset(55);
        make.top.mas_equalTo(topView.mas_top).offset(80);
        make.width.mas_equalTo(95);
        make.height.mas_equalTo(40);
    }];
    
    [setBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(topView.mas_right).offset(-55);
        make.top.mas_equalTo(topView.mas_top).offset(80);
        make.width.mas_equalTo(95);
        make.height.mas_equalTo(40);
        
    }];
    
    [sepline mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(setBtn.mas_bottom).offset(80);
        make.left.right.equalTo(topView);
        make.height.mas_equalTo(0.5);
    }];
    
    [predictTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(sepline.mas_top).offset(-5);
        make.left.mas_equalTo(topView.mas_left).offset(15);
    }];
    
    
    return topView;
}

#pragma mark -- Nav
- (void)setNav {
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 80, 20)];
    imageView.image = kSET_IMAGE(@"HomeTitle");
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:imageView];
    self.navigationItem.leftBarButtonItem = leftItem;
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [btn setImageEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
    [btn addTarget:self action:@selector(ReadMessage:) forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:[UIImage imageNamed:@"message_white"] forState:UIControlStateNormal];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    [self.navigationItem setRightBarButtonItem:rightItem];
}
//查看消息
- (void)ReadMessage:(UIButton *)sender {
    MessageViewController *messageVc = [MessageViewController new];
    messageVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:messageVc animated:YES];
}

#pragma mark -- tableView 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _orderbyDateArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableArray *array = [NSMutableArray array];
    array = _orderbyDateArray[section];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    StarHomeModel *model = _orderbyDateArray[indexPath.section][indexPath.row];
    HomeStarCell *cell = [HomeStarCell loadNibCellWithTabelView:self.tableView];
    cell.homeModel = model;
    if (indexPath.section == _orderbyDateArray.count - 1) {
        cell.bottomline.hidden = YES;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}



#pragma mark -- 区头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    HomeStarTopView *topView = [[NSBundle mainBundle] loadNibNamed:@"HomeStarTopView" owner:self options:nil].lastObject;
    StarHomeModel *model = _orderbyDateArray[section][0];
    topView.dateLabel.text = [model.l_date substringFromIndex:5];
    NSString *timeStr = [NSString stringWithFormat:@"%@ %@",model.l_date,model.l_startime];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *compareDate = [[NSDate alloc] init];
    compareDate = [formatter dateFromString:timeStr];
    NSString *tipStr = [self compareDate:compareDate];
    if (tipStr.length) {
        topView.DateTips.hidden = NO;
        topView.DateTips.text = tipStr;
    } else {
        topView.DateTips.hidden = YES;
    }
    if (section == 0) {
        topView.topline.hidden = YES;
    }
    if (section == _orderbyDateArray.count - 1) {
        topView.bottomline.hidden = YES;
    }
    return topView;
}

//开始直播
- (void)BeginLiving:(UIButton *)sender {
    LivingViewController *livingVc = [LivingViewController new];
    [self presentViewController:livingVc animated:YES completion:nil];
  
}

//设定预播
- (void)PredictClick:(UIButton *)sender {
    SetPredictViewController *setVc = [[SetPredictViewController alloc] init];
    setVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:setVc animated:YES];
    setVc.hidesBottomBarWhenPushed = NO;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 30;
}

#pragma mark -- 比较时间
-(NSString *)compareDate:(NSDate *)date{
    
    NSTimeInterval secondsPerDay = 24 * 60 * 60;
    NSDate *today = [[NSDate alloc] init];
    NSDate *tomorrow, *yesterday;
    
    tomorrow = [today dateByAddingTimeInterval: secondsPerDay];
    yesterday = [today dateByAddingTimeInterval: -secondsPerDay];
    
    // 10 first characters of description is the calendar date:
    NSString * todayString = [[today description] substringToIndex:10];
    NSString * yesterdayString = [[yesterday description] substringToIndex:10];
    NSString * tomorrowString = [[tomorrow description] substringToIndex:10];
    
    NSString * dateString = [[date description] substringToIndex:10];
    
    if ([dateString isEqualToString:todayString])
    {
        return @"今天";
    } else if ([dateString isEqualToString:yesterdayString])
    {
        return @"昨天";
    }else if ([dateString isEqualToString:tomorrowString])
    {
        return @"明天";
    }
    else
    {
        return @"";
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
